import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import apiClient from '../axios/axios';
import { useUserStore } from './user';
import { ElMessage } from 'element-plus';

interface CartItem {
  productId: number;
  productName: string;
  imageUrl: string;
  quantity: number;
  price: number;
}

interface CartResponse {
  items: CartItem[];
  totalAmount: number;
}

export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore();

  const items = ref<CartItem[]>([]);
  const totalAmount = ref(0);
  const isLoading = ref(false);

  const totalQuantity = computed(() => {
    return items.value.reduce((sum, item) => sum + item.quantity, 0);
  });

  const cart = computed(() => ({
    items: items.value,
    totalAmount: totalAmount.value,
    totalQuantity: totalQuantity.value,
  }));

  function updateCartState(data: CartResponse) {
    items.value = data.items;
    totalAmount.value = data.totalAmount;
  }

  async function getCart() {
    if (!userStore.isLoggedIn || !userStore.user) return;
    isLoading.value = true;
    try {
      const response = await apiClient.get<CartResponse>('/cart', {
        params: { userId: userStore.user.id },
      });
      updateCartState(response.data);
    } catch (error) {
      console.error('Failed to fetch cart:', error);
      ElMessage.error('获取购物车失败');
    } finally {
      isLoading.value = false;
    }
  }

  async function addItem(productId: number, quantity: number) {
    if (!userStore.isLoggedIn || !userStore.user) {
        ElMessage.warning('请先登录');
        // Optionally, trigger login dialog
        return;
    }
    isLoading.value = true;
    try {
        const response = await apiClient.post<CartResponse>('/cart/items', 
            { productId, quantity },
            { params: { userId: userStore.user.id } }
        );
        updateCartState(response.data);
        ElMessage.success('已添加到购物车');
    } catch (error) {
        console.error('Failed to add item to cart:', error);
        ElMessage.error('添加失败，请稍后重试');
    } finally {
        isLoading.value = false;
    }
  }

  async function updateItemQuantity(productId: number, quantity: number) {
    if (!userStore.isLoggedIn || !userStore.user) return;
    isLoading.value = true;
    try {
        const response = await apiClient.put<CartResponse>(`/cart/items/${productId}`, 
            { quantity },
            { params: { userId: userStore.user.id } }
        );
        updateCartState(response.data);
    } catch (error) {
        console.error('Failed to update item quantity:', error);
        ElMessage.error('更新数量失败');
    } finally {
        isLoading.value = false;
    }
  }

  async function removeItem(productId: number) {
    if (!userStore.isLoggedIn || !userStore.user) return;
    isLoading.value = true;
    try {
        const response = await apiClient.delete<CartResponse>(`/cart/items/${productId}`, {
            params: { userId: userStore.user.id },
        });
        updateCartState(response.data);
        ElMessage.success('商品已移除');
    } catch (error) {
        console.error('Failed to remove item from cart:', error);
        ElMessage.error('移除失败');
    } finally {
        isLoading.value = false;
    }
  }

  async function clearCart() {
    if (!userStore.isLoggedIn || !userStore.user) return;
    isLoading.value = true;
    try {
      await apiClient.delete('/cart', {
        params: { userId: userStore.user.id },
      });
      // Clear state locally
      items.value = [];
      totalAmount.value = 0;
      ElMessage.success('购物车已清空');
    } catch (error) {
      console.error('Failed to clear cart:', error);
      ElMessage.error('清空购物车失败');
    } finally {
      isLoading.value = false;
    }
  }

  function clearLocalCartState() {
    items.value = [];
    totalAmount.value = 0;
  }

  return {
    cart,
    isLoading,
    getCart,
    addItem,
    updateItemQuantity,
    removeItem,
    clearCart,
    clearLocalCartState,
  };
}); 